package web.java.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownLoad extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String method=request.getParameter("method");
		if("download".equals(method)){
			download(request,response);
		}
	}
	protected void download(HttpServletRequest request,HttpServletResponse response) 
			throws ServletException, IOException{
		//1、获取文件夹路径
		String path=getServletContext().getRealPath("/upload");
		//2、获取文件名
		String str=request.getParameter("fileName");
		//处理get请求乱码
		String name=new String(str.getBytes("ISO-8859-1"),"utf-8");
		//3、获取文件
		path=path+"/"+name;
		File file=new File(path);
		FileInputStream in=new FileInputStream(file);
		byte[] buf=new byte[1024];
		//4、设置下载的响应头
		response.setHeader("content-disposition","attachment; fileName="+name);
		OutputStream out=response.getOutputStream();
		int len=-1;
		while((len=in.read(buf))!=-1){
			out.write(buf,0,len);
		}
		out.close();
		in.close();
	}
}
